/**
 * @Title: BindController.java
 * @Package com.leesche.zcsp.node.web.controller.wechat.bind.bind
 * @Description:()
 * @author dennies yang
 * @date 2016年10月20日 下午3:04:35
 * @version V1.0
 */
package com.leesche.zcsp.node.app.v1.controller.bind;

import com.leesche.zcsp.node.utils.UUIDGenerateUtil;
import com.leesche.zcsp.node.utils.web.PagingResult;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.WebUtils;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.PubDevice;
import com.leesche.zcsp.node.web.service.LPubDeviceSerice;
import com.leesche.zcsp.node.web.service.PubDeviceService;
import com.leesche.zcsp.node.web.service.PubDevicetypeService;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.v2.OnLineVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dennies yang
 * @version V1.0
 * @Title: BindController.java
 * @Package com.leesche.zcsp.node.web.controller.wechat.bind.bind
 * @Description:(绑定控制)
 * @date 2016年10月20日 下午3:04:35
 */
@Controller
@RequestMapping(value = "/app/v1/bind")
public class AppBindController {
    private static final Logger logger = Logger.getLogger(AppBindController.class);

    @Autowired
    PubDeviceService pubDeviceService;

    @Autowired
    LPubDeviceSerice lPubDeviceSerice;

    @Autowired
    PrivilegeService privilegeService;

    @Autowired
    PubDevicetypeService pubDevicetypeService;


    @ResponseBody
    @RequestMapping(value = "listDevType", method = RequestMethod.POST)
    public Map<String, Object> add(HttpSession session,HttpServletRequest request) {
        Long userid=privilegeService.getCurrentPrincipalForApp()==null?1L:privilegeService.getCurrentPrincipalForApp().getUserid();
        QueryPubDeviceTypeCondition queryPubDeviceTypeCondition=new QueryPubDeviceTypeCondition();
        queryPubDeviceTypeCondition.setAdminId(userid);
        try{
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("devicetype",   pubDevicetypeService.findListsByCondition(queryPubDeviceTypeCondition));
            return WebResult.success().put("data", map).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }



    }

    /**
     * @param @param  imme 设备唯一码
     * @param @param  shortCode 设备解码
     * @param @param  payCode 设备支付码
     * @param @param  session
     * @param @return
     * @return Map<String,Object>
     * @throws
     * @Title: add
     * @Description: TODO(绑定保存)
     */
    @ResponseBody
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Map<String, Object> add(String imme, String shortCode, String payCode,Long devTypeid,
                                  /* @RequestParam(value = "file", required = false) MultipartFile imageUploadFile,*/HttpSession session,HttpServletRequest request) {
        MultipartFile  imageUploadFile=null;
        if(request instanceof MultipartHttpServletRequest){
            imageUploadFile=((MultipartHttpServletRequest) request).getFile("file");
        }

        if(privilegeService.getCurrentPrincipalForApp()==null){
            return WebResult.failure("权限不足,请重新登录").toMap();
        }
        if(StringUtils.isBlank(imme)||StringUtils.isBlank(shortCode)||StringUtils.isBlank(payCode)){
            return WebResult.failure("数据输入错误！").toMap();
        }
        if(imageUploadFile==null || imageUploadFile.isEmpty()){
            return WebResult.failure("请选择流量卡图片").toMap();
        }

        // 获取设备信息
        PubDeviceDto pubDeviceDto =this.findPubDeviceDto(imme, null, null);
        if(pubDeviceDto==null){
            return WebResult.failure("设备未注册").toMap();
        }
        //设备已经绑定简码
        if(StringUtils.isNotBlank(pubDeviceDto.getDeviceshortcode())){
            return WebResult.failure("设备已绑定简码："+pubDeviceDto.getDeviceshortcode()).toMap();
        }
        //设备已经绑定支付码
        if(StringUtils.isNotBlank(pubDeviceDto.getMac())){
            return WebResult.failure("设备已绑定支付码:"+pubDeviceDto.getMac()).toMap();
        }

        if(pubDeviceDto!=null){
            // 判断设备是否已经绑定过了
            if(StringUtils.isNotEmpty(pubDeviceDto.getMac())){
                return WebResult.failure("设备已经绑定").toMap();
            }
        }



        // 判断支付码是否绑定
        if(this.findPubDeviceDto(null, shortCode, null)!=null){
            return WebResult.failure("设备简码已使用过").toMap();
        }
        // 判断解码是否绑定过
        if(this.findPubDeviceDto(null, null, payCode)!=null){
            return WebResult.failure("设备支付码已使用过").toMap();
        }


        try {
            //执行绑定操作

            PubDevice pubDevice=pubDeviceService.selectByPrimaryKey(pubDeviceDto.getDeviceid());
            pubDevice.setImme(imme);
            pubDevice.setMac(payCode);
            pubDevice.setDeviceshortcode(shortCode);
            pubDevice.setDevicetypeid(devTypeid);
            pubDevice.setAgentid(privilegeService.getCurrentPrincipalForApp()==null?1L:privilegeService.getCurrentPrincipalForApp().getUserid());
            if(pubDeviceDto==null){
		/*		if(pubDeviceService.insert(pubDevice)>0){*/
                return WebResult.success().info("设备未注册!").toMap();
			/*	}*/

            }else {
                String fileName = imageUploadFile.getOriginalFilename();
                String extName = fileName.substring(fileName.lastIndexOf("."));

                if (!WebUtils.checkIsImage(extName)
                        && !imageUploadFile.getContentType().matches("image.*")) {
                    return WebResult.failure("上传的文件必须是图片!").toMap();
                }

                String hexString = WebUtils.getFileHexString(imageUploadFile.getInputStream());

                boolean flag = false;
                String[] magic = Constants.SYSTEM_IMAGE_MAGICNUMBER;
                for (int i = 0; i < magic.length; i++) {
                    if (magic[i].equals(hexString)) {
                        flag = true;
                        break;
                    }
                }

                if (flag == false) {
                    return WebResult.failure("上传的文件不是图片类型").toMap();
                }

                if (imageUploadFile.getSize() > Constants.SYSTEM_IMAGE_SIZE) {
                    return WebResult.failure("上传的图片实在是太大了,不能超过" + Constants.SYSTEM_IMAGE_SIZE + "M").toMap();
                }


                String imagePath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_DEVICE_DIRECTORY);
                String imageName = UUIDGenerateUtil.generateUUID() + extName;

                File imageFile = new File(imagePath, imageName);

                if (!imageFile.exists()) {
                    imageFile.mkdirs();
                }

                imageUploadFile.transferTo(imageFile);
                pubDevice.setSdata5(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_DIRECTORY + "/" + imageName);
                if(pubDeviceService.editPubDeviceByImme(pubDevice)>0){
                    return WebResult.success().info("绑定成功").toMap();
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
        return WebResult.failure("绑定失败").toMap();


    }

    @ResponseBody
    @RequestMapping(value = "setDevType", method = RequestMethod.POST)
    public Map<String, Object> setDevType(Long devTypeid,Long deviceId){
        try{
           Long adminId= privilegeService.getCurrentPrincipalForApp()==null?1L:privilegeService.getCurrentPrincipalForApp().getUserid();
            PubDevice pubDevice=pubDeviceService.selectByPrimaryKey(deviceId);
            if(pubDevice!=null&&pubDevice.getAgentid()!=null&&adminId!=null&&adminId.equals(pubDevice.getAgentid())){
                pubDevice.setDevicetypeid(devTypeid);
                pubDeviceService.updateByPrimaryKey(pubDevice);
            }

            return WebResult.success().info("更新成功").toMap();

        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return WebResult.failure("更新失败").toMap();

    }

    /***
     * @param @param  imme
     * @param @param  shortCode
     * @param @param  payCode
     * @param @return
     * @return condition
     * @throws
     * @Title: findPubDeviceDto
     * @Description: TODO(查询设备信息)
     */
    private PubDeviceDto findPubDeviceDto(String imme, String shortCode, String payCode) {
        QueryPubDeviceCondition condition = new QueryPubDeviceCondition();
        condition.setImme(imme);
        condition.setMac(payCode);
        condition.setDeviceshortcode(shortCode);
        return pubDeviceService.findByCondition(condition);
    }
    @ResponseBody
    @RequestMapping(value = "/countDevice", method = RequestMethod.POST)
    public Map<String,Object> batchDelCoupon(
           String imei,String date,Integer page,Integer rows
    ){
        try{
            if(StringUtils.isBlank(imei)){
                return WebResult.failure("imei不能为空").toMap();
            }
            if(StringUtils.isBlank(date)){
                return WebResult.failure("日期必须输入").toMap();
            }
            if(page==null){
                page=1;
            }
            if(rows==null){
                rows=20;
            }

            QueryLPubDeviceCondition condition=new QueryLPubDeviceCondition();
            condition.setImei(imei);
            condition.setStartDate(date);
            condition.setPage(page);
            condition.setRows(rows);
            java.util.List<OnLineVo> onLineVos =lPubDeviceSerice.countOnline(condition);
            PagingResult<LPubDeviceDto> devLogs = lPubDeviceSerice.findAllByPage(condition);

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("onLineVos", onLineVos);
            map.put("devLogs", devLogs);
            return WebResult.success().put("data",map).toMap();

        }catch (Exception e){
            return WebResult.failure("查询失败").toMap();
        }
    }

}
